package com.yonyou.gmmc.service.wechatpush.provider.impl;

import org.apache.log4j.Logger;
import org.marketing.common.constants.MessagePushConstant;
import org.marketing.common.entity.wechatpushmessage.WeChatMessageProtocol;
import org.marketing.common.util.CommonUtils;
import org.marketing.common.util.SerializeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yonyou.gmmc.service.wechatpush.common.WechatDict;
import com.yonyou.gmmc.service.wechatpush.provider.MessageProvideAdapter;
import com.yonyou.gmmc.service.wechatpush.provider.MessagePushResult;
import com.yonyou.gmmc.service.wechatpush.provider.ProviderMessage;
import com.yonyou.gmmc.service.wechatpush.resolver.PushMessage;
import com.yonyou.gmmc.service.wechatpush.service.TokenService;
import com.yonyou.gmmc.service.wechatpush.service.WechatLocalTemplateService;
import com.yonyou.gmmc.service.wechatpush.spi.webchattools.WebChatTemplateMessage;
import com.yonyou.gmmc.service.wechatpush.spi.webchattools.WxMpSendTemplateMessageResponse;
import com.yonyou.gmmc.service.wechatpush.spi.webchattools.WxMpTemplateMsgService;

@Service("MessageProvideAdapterLocalImpl")
public class MessageProvideAdapterLocalImpl implements MessageProvideAdapter {

	private final static Logger logger = Logger.getLogger(MessageProvideAdapterImpl.class);

	@Autowired
	private TokenService tokenService;
	@Autowired
	private WechatLocalTemplateService wxTemplateService;

	@Autowired
	private WxMpTemplateMsgService service;

	@Override
	public MessagePushResult push2Provider(ProviderMessage providerMessage) {
		if (providerMessage == null) {
			logger.error("ProviderMessage is null");
			return new MessagePushResult(false, "ProviderMessage is null");
		}
		MessagePushResult result;
		WeChatMessageProtocol origin = providerMessage.getOrigin().getOrigin();
		if (origin.getPushChannel().equals(MessagePushConstant.PUSH_CHANNEL.TEST)) {
			result = new MessageDemoProvide().pushDemoMessage(providerMessage);
		}
		// web chat
		else if (origin.getPushChannel().equals(MessagePushConstant.PUSH_CHANNEL.WEBCHAT)) {
			result = pushTemplateMessage(providerMessage);
		} else {
			logger.error("ProviderMessage channel is error");
			result = new MessagePushResult(false, "ProviderMessage channel is error");
		}
		log2DataBase(providerMessage, result);
		return result;

	}

	/**
	 * 记录日志
	 * 
	 * @param providerMessage
	 *            ProviderMessage
	 * @param result
	 *            MessagePushResult
	 */
	// @Transactional
	private void log2DataBase(ProviderMessage providerMessage, MessagePushResult result) {
		// logger.debug("@@result = "+result);
		// List<String> receiverList =
		// providerMessage.getOrigin().getOrigin().getReceiver().getDetailList();
		// if(CommonUtils.isNullOrEmpty(receiverList)){
		// logger.warn("rabbitMq message-receiverList is empty");
		// return;
		// }
		// //记录消息
		// for(String receiverId:receiverList){
		// PushMessageHandleHistory history = new
		// PushMessageHandleHistory(providerMessage,result,receiverId);
		// repository.save(history);
		// }
	}

	@Override
	public ProviderMessage trans2Provider(PushMessage pushMessage) {
		if (pushMessage.getOrigin().getPushChannel().equals(MessagePushConstant.PUSH_CHANNEL.TEST)) {
			ProviderMessage message = new ProviderDemoMessage();
			message.fillContent(pushMessage);
			return message;
		}
		if (pushMessage.getOrigin().getPushChannel().equals(MessagePushConstant.PUSH_CHANNEL.WEBCHAT)) {
			return transTemplate(pushMessage);
		} else {
			return null;
		}
	}

	public ProviderMessage transTemplate(PushMessage pushMessage) {
		if (pushMessage.getOrigin().getReceiver().getPlatform().equals(MessagePushConstant.PUSH_PLATFORM.WC_PUBLIC)) {
			ProviderMessage message = new WebChatTemplateMessage();
			message.fillContent(pushMessage);
			return message;
		} else {
			return null;
		}
	}

	/**
	 * 实际调用方法
	 * 
	 * @param providerMessage
	 *            providerMessage
	 * @param accessToken
	 *            accessToken
	 * @return MessagePushResult
	 */
	public MessagePushResult pushTemplateMessage(ProviderMessage providerMessage, String accessToken) {
		if (providerMessage.getPlatForm().equals(MessagePushConstant.PUSH_PLATFORM.WC_PUBLIC)) {
			WebChatTemplateMessage message = (WebChatTemplateMessage) providerMessage;
			int size = message.getOrigin().getOrigin().getReceiver().getDetailList().size();
			logger.debug("WebChatTemplateMessage is " + message);
			// 根据shortID动态获取templateId
			String templateShortId = message.getOrigin().getOrigin().getMessage().getContent();
			String authorizerAppid = WechatDict.appid;

			if (CommonUtils.isNullOrEmpty(templateShortId) || CommonUtils.isNullOrEmpty(authorizerAppid)) {
				logger.error("send params is empty,templateShortId or authorizerAppid");
				return new MessagePushResult(false, "send params is empty,templateShortId or authorizerAppid");

			}

			// 获取模板ID
			String templateId = wxTemplateService.getDealerWoTemplateId("", templateShortId);

			logger.info("pushTemplateMessage-templateId=" + templateId);
			message.getMessage().setTemplateId(templateId);
			WxMpSendTemplateMessageResponse result = null;
			for (int i = 0; i < size; i++) {
				message.getMessage().setToUser(message.getOrigin().getOrigin().getReceiver().getDetailList().get(i));
				logger.info(
						"pushTemplateMessage-message.getMessage()=" + SerializeUtils.serialize(message.getMessage()));

				// 发送模板
				result = service.sendTemplateMsg(message.getMessage(), accessToken);
				if (result == null || !result.isSucceed()) {
					return new MessagePushResult(false, "send Template message error");
				}
				logger.info("WebChatTemplateMessage result is " + result.getMessageId());
			}
			if (result != null) {
				return new MessagePushResult(true, result.getMessageId());
			}

		}
		logger.error("error platform ");
		return new MessagePushResult(false, "error platform ");
	}

	private MessagePushResult pushTemplateMessage(ProviderMessage providerMessage) {
		if (providerMessage.getPlatForm().equals(MessagePushConstant.PUSH_PLATFORM.WC_CUSTOMER)) {
			return new MessagePushResult(false, "暂时不支持客服消息");
		}
		// 使用
		String accessToken;
		try {
			accessToken = tokenService.getAccessToken();
		} catch (Exception e) {
			logger.error(e);
			return new MessagePushResult(true, e.getMessage());
		}
		if (CommonUtils.isNullOrEmpty(accessToken)) {
			logger.error("access token is null");
			return new MessagePushResult(true, "access token is null");
		}
		return pushTemplateMessage(providerMessage, accessToken);
	}

}
